package com.yfbao.horizon.demo;

import cn.hutool.core.io.FileUtil;
import com.yfbao.horizon.utils.FileLocalUtils;

import java.util.ArrayList;
import java.util.List;

public class LogAnalysis {

    public static void main(String[] args) {
        String src ="C:\\Users\\byf78\\Desktop\\日志分析\\性能接口\\ctp-user-info.log.2023-09-14.43";
        getfifterDubboCost(src,2000);
    }

    /**
     * 解析出日志中耗时超过阈值的日记录
     * @param srcFile
     * @param costOver
     */
    private static void getfifterDubboCost(String srcFile,Integer costOver){
        System.out.println("----begin analysis------------------------------------");
        String outFile = "C:\\Users\\byf78\\Desktop\\日志分析\\性能接口\\ctp-user-info-cost.log";
        String fifter ="Dubbo调用耗时=[";
//        List<String> stringList = FileLocalUtils.fifterLog(file, null);
        List<String> stringList = FileLocalUtils.fifterLog(srcFile, fifter);
        List<String> resList = new ArrayList<>();
        for (String str : stringList) {
            String[] split = str.split("Dubbo调用耗时");
            if(split.length<=1){
                System.out.println("数据异常："+str);
                continue;
            }
            String s = split[1];
            int start = s.trim().indexOf("=[");
            int end = s.trim().indexOf("]", start + 1);
            String substring = s.substring(start + 2, end);
            if(!substring.endsWith("ms") || substring.length()<=2){
                System.out.println("数据异常："+str);
                continue;
            }
            substring =substring.substring(0,substring.length()-2);
            try {
                Integer cost = Integer.valueOf(substring);
                if(cost>=costOver){
                    resList.add(str);
                }
            }catch (Exception e){
                System.out.println("数据异常："+str);
            }
        }
        System.out.println("----finish analysis------------------------------------");
        if(resList.size()>0){
            FileUtil.writeLines(resList,outFile,"utf-8");
        }
    }
}
